package com.bc.web.controller.admin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.bc.web.config.SystemEnum;
import com.bc.web.model.Channel;
import com.bc.web.model.ClearingCollect;
import com.bc.web.model.ClearingDetail;
import com.bc.web.model.Dictionary;
import com.bc.web.model.TradeOrder;
import com.fs.common.extend.FSController;
import com.fs.common.extend.FSSearchCondition;
import com.fs.common.extend.FSSqlHelper;
import com.fs.common.util.FSDate;
import com.fs.common.util.FSIDGenerate;
import com.fs.common.util.FSJedis;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class ClearingDetailController extends FSController {
	private static final String CREATE_COLLECT_NUMBER = "CREATE_COLLECT_NUMBER";

	/**
	 * 查询本地差错
	 */
	public void searchLocalError() {
		FSSearchCondition sc = super.getSearchCondition();
		sc.setParameter("compareStatus1", SystemEnum.CompareStatus.LocalError.getValue());
		sc.setParameter("compareStatus2", SystemEnum.CompareStatus.LocalErrorSuccess.getValue());
		setPageResultToRequest("items", ClearingDetail.dao.search(sc));
		setAttr("payTypeList", Dictionary.dao.selectByParentKey("payType"));
		render("clearing/detail/localErrorList.html");
	}
	
	/**
	 * 本地差错处理页面
	 */
	public void localErrorHandlePage() {
		setAttr("channelList",  Channel.dao.selectAll());
		setAttr("payTypeList",  Dictionary.dao.selectByParentKey("payType"));
		setAttr("clearingDetail",  ClearingDetail.dao.findById(getPara("id")));
		render("clearing/detail/localErrorHandle.html");
	}
	
	/**
	 * 本地差错处理
	 */
	public void localErrorHandle() {
		ClearingDetail clearingDetail = getModel(ClearingDetail.class);
		clearingDetail.update();
		renderSuccess();
	}

	/**
	 * 查询渠道差错
	 */
	public void searchChannelError() {
		FSSearchCondition sc = super.getSearchCondition();
		sc.setParameter("compareStatus1", SystemEnum.CompareStatus.ChannelError.getValue());
		sc.setParameter("compareStatus2", SystemEnum.CompareStatus.ChannelErrorSuccess.getValue());
		Page<ClearingDetail> pageResult = ClearingDetail.dao.search(sc);
		setAttr("payTypeList", Dictionary.dao.selectByParentKey("payType"));
		setPageResultToRequest("items", pageResult);
		render("clearing/detail/channelErrorList.html");
	}

	/**
	 * 渠道差错处理页面
	 */
	public void channelErrorHandlePage() {
		ClearingDetail clearingDetail = ClearingDetail.dao.findById(getPara("id"));
		TradeOrder virtualOrder = TradeOrder.dao.selectByOrderNo(clearingDetail.getOrderNo());
		setAttr("channelList", Channel.dao.selectAll());
		setAttr("payTypeList", Dictionary.dao.selectByParentKey("payType"));
		setAttr("clearingDetail", clearingDetail);
		setAttr("virtualOrder", virtualOrder);
		render("clearing/detail/channelErrorHandle.html");
	}

	/**
	 * 渠道差错处理
	 */
	public void channelErrorHandle() {
		String feeStr = getPara("fee");
		BigDecimal fee = new BigDecimal(feeStr).multiply(new BigDecimal("100"));
		ClearingDetail detail = getModel(ClearingDetail.class);
		detail.setFee(fee.intValue());
		detail.update();
		renderSuccess();
	}

	/**
	 * 明细风控查询
	 */
	public void detailRiskSearch() {
		FSSearchCondition sc = super.getSearchCondition();
		sc.setParameter("isRisk", "true");
		Page<ClearingDetail> pageResult = ClearingDetail.dao.search(sc);
		setPageResultToRequest("items", pageResult);
		render("clearing/detail/detailRiskList.html");
	}

	/**
	 * 明细冻结页面
	 */
	public void detailFreezePage() {
		render("clearing/detail/detailFreeze.html");
	}

	/**
	 * 明细冻结
	 */
	public void detailFreeze() {
		ClearingDetail detail = ClearingDetail.dao.selectFreezeOrderByOrderNo(getPara("clearingDetail.orderNo"));
		if (detail == null) {
			renderFail();
		}else {
			detail.setIsRisk(true);
			detail.setPaymentStatus(SystemEnum.PaymentStatus.Freeze.getValue());
			detail.setFreezeTime(FSDate.getDateTime());
			detail.update();
			renderSuccess();
		}
	}

	/**
	 * 明细解冻页面
	 */
	public void detailThawPage() {
		setAttr("channelList", Channel.dao.selectAll());
		setAttr("payTypeList",  Dictionary.dao.selectByParentKey("payType"));
		setAttr("clearingDetail", ClearingDetail.dao.findById(getPara("id")));
		render("clearing/detail/detailThaw.html");
	}

	/**
	 * 明细解冻
	 */
	public void detailThaw() {
		ClearingDetail clearingDetail = getModel(ClearingDetail.class);
		clearingDetail.setPaymentStatus(SystemEnum.PaymentStatus.Thaw.getValue());
		clearingDetail.setThawTime(FSDate.getDateTime());
		clearingDetail.update();
		renderSuccess();
	}

	/**
	 * 查询明细
	 */
	public void searchDetail() {
		Page<ClearingDetail> pageResult = ClearingDetail.dao.search(super.getSearchCondition());
		List<Object> list = ClearingDetail.dao.searchSum(super.getSearchCondition());
		Object[] value = (Object[]) list.get(0);
		setAttr("sumCount", value[0]);
		setAttr("sumAmount", value[1] == null ? "0" : value[1]);
		setAttr("sumFee", value[2] == null ? "0" : value[2]);
		setPageResultToRequest("items", pageResult);
		render("clearing/detail/detailList.html");
	}

	/**
	 * 查看明细
	 */
	public void viewDetail() {
		ClearingDetail clearingDetail = ClearingDetail.dao.findById(getPara("id"));
		setAttr("channelList", Channel.dao.selectAll());
		setAttr("payTypeList", Dictionary.dao.selectByParentKey("payType"));
		setAttr("clearingDetail", clearingDetail);
		render("clearing/detail/detailView.html");
	}

	/**
	 * 生成出账数据
	 */
	@Before(Tx.class)
	public void createCollect() {
		long number = FSJedis.increment(CREATE_COLLECT_NUMBER);
		if (number == 1) {
			String sql = "SELECT channelCode,orgCode,merchCode,COUNT(*) AS sumCount,SUM(amount) AS sumAmount, SUM(fee) AS sumFee FROM clearing_detail WHERE paymentStatus IN(?,?) AND compareStatus IN(?,?,?) GROUP BY channelCode,orgCode,merchCode";
			List<Record> paymentList = Db.find(sql, SystemEnum.PaymentStatus.Init.getValue(),
					SystemEnum.PaymentStatus.Thaw.getValue(),
					SystemEnum.CompareStatus.LocalErrorSuccess.getValue(),
					SystemEnum.CompareStatus.ChannelErrorSuccess.getValue(),
					SystemEnum.CompareStatus.Success.getValue());
			List<ClearingCollect> collectList = new ArrayList<>();
			List<String> merchCodeList = new ArrayList<>();
			if (paymentList.size() > 0) {
				for (int i = 0; i < paymentList.size(); i++) {
					String merchCode = paymentList.get(i).getStr("merchCode");
					long amount = paymentList.get(i).getBigDecimal("sumAmount").longValue();
					if (amount > 0) {
						// 结果冻结处理
						List<ClearingCollect> freezeList = ClearingCollect.dao.selectFreezeData(merchCode);
						if (freezeList.size() > 0) {
							for (int j = 0; j < freezeList.size(); j++) {
								if (amount > 0) {
									ClearingCollect fc = freezeList.get(j);
									long freezeAmount = fc.getFreezeAmount() - fc.getAmount();
									if (amount >= freezeAmount) {
										fc.setAmount(fc.getAmount() + freezeAmount);
										fc.setLastFreezeAmount(freezeAmount);
										fc.setFreezeTime(FSDate.getDateTime());
										fc.update();
										amount = amount - freezeAmount;
									} else {
										fc.setAmount(fc.getAmount() + amount);
										fc.setLastFreezeAmount(amount);
										fc.setFreezeTime(FSDate.getDateTime());
										fc.update();
										amount = 0L;
									}
								} else {
									break;
								}
							}
						}

						// 出账结果生成
						if (amount > 0) {
							ClearingCollect c = new ClearingCollect();
							c.setId(FSIDGenerate.getUUID());
							c.setOrderNo(FSIDGenerate.nextOrderNo());
							c.setChannelCode(paymentList.get(i).getStr("channelCode"));
							c.setOrgCode(paymentList.get(i).getStr("orgCode"));
							c.setMerchCode(merchCode);
							c.setSumCount(paymentList.get(i).getLong("sumCount").longValue());
							c.setAmount(amount);
							c.setFee(paymentList.get(i).getBigDecimal("sumFee").longValue());
							c.setPaymentAmount(amount + paymentList.get(i).getBigDecimal("sumFee").longValue());
							c.setCreateDate(FSDate.getDate());
							c.setPaymentStatus(SystemEnum.PaymentStatus.Init.getValue());
							c.setCreateTime(FSDate.getDateTime());
							c.setIsRisk(false);
							collectList.add(c);
							merchCodeList.add(c.getMerchCode());
						}
					}
				}
			}
			if (paymentList.size() > 0) {
				if (collectList.size() > 0) {
					Db.batchSave(collectList, collectList.size());
				}
				if (merchCodeList.isEmpty() == false) {
					FSSqlHelper updateSql = new FSSqlHelper("UPDATE clearing_detail SET paymentStatus='5' WHERE 1 = 1 ");
					updateSql.in("paymentStatus", SystemEnum.PaymentStatus.Init.getValue(),
							SystemEnum.PaymentStatus.Thaw.getValue());
					updateSql.in("merchCode", merchCodeList.toArray());
					updateSql.in("compareStatus", SystemEnum.CompareStatus.LocalErrorSuccess.getValue(),
							SystemEnum.CompareStatus.ChannelErrorSuccess.getValue(),
							SystemEnum.CompareStatus.Success.getValue());
					Db.update(updateSql.toString(), updateSql.getParams());
				}
				renderSuccess("生成出账结果数据成功！");
			} else {
				renderFail("无数据！");
			}
			FSJedis.remove(CREATE_COLLECT_NUMBER);
			return;
		}
		renderFail("不能重复执行！");
	}

}
